;!function(window){

var CT_MENU_MOD = function(options){
	this.v = '1.0.0';
	this.options = options;
	this.target = {};
	this.init();
	}

CT_MENU_MOD.fn = CT_MENU_MOD.prototype;
CT_MENU_MOD.fn.className = 'yan-context-menu';
CT_MENU_MOD.fn.stopProp = function (e) {
    if (e.cancelable) {
        // 判断默认行为是否已经被禁用
        if (!e.defaultPrevented) {
            e.preventDefault();
        }
    }
    e.stopPropagation();
};
CT_MENU_MOD.fn.render = function (e, trigger) {
	var that = this;
	var x=e.clientX,y=e.clientY;
    that.stopProp(e);
    that.hide();
    that.target = e.target;
    var node = that.menu(that.options.menu, e);
	node.style.left = e.clientX + 'px';
	node.style.top = e.clientY + 'px';
    document.body.append(node);
    that.fix(e, node);
};
CT_MENU_MOD.fn.fix = function(e,node){
	var window_height = document.body.offsetHeight;
	var node_height = node.offsetHeight + e.clientY;
	if(node_height - window_height >0){
		var current = document.getElementById(node.id);
		var cha = node_height - window_height + 30;
		current.style.top = e.clientY - cha + 'px';
	}
}
CT_MENU_MOD.fn.menu = function (menu, event) {
	var that = this;
	var node = document.createElement("div");
	node.id=that.className;
	node.className=that.className;
	if(menu){
		node.classList.add("has-child");
		var nodeUl = document.createElement("ul");
		nodeUl.className = " submenu";
		for(var x of menu){
			nodeUl.append(that.menuItem(x, event));
		}
		node.append(nodeUl);
	}
	return node;
};
CT_MENU_MOD.fn.menuItem = function (menu, event) {
	var that = this;
	var node = document.createElement("li");
	node.append(menu["label"]);
	if(menu.onclick){
		node.addEventListener("click", function(e){
			that.hide();
			menu.onclick(e, event);
		});
	}
	if(menu["child"]){
		node.classList.add("has-child");
		var nodeUl = document.createElement("ul");
		nodeUl.className = "submenu";
		for(var x of menu["child"]){
			nodeUl.append(that.menuItem(x, target));
		}
		node.append(nodeUl);
	}
	return node;
};
CT_MENU_MOD.fn.hide = function (e) {
	var that = this;
    if(document.querySelector("."+that.className)){
		document.querySelector("."+that.className).remove();
	}
};
CT_MENU_MOD.fn.handle = function () {
	var that = this;
    if(that.options['ele']){
		var doc = document.querySelector(that.options['ele']);
	}
	doc = doc || document;
	$(document).on("contextmenu", that.options['ele'], function(e){
		that.render(e, that);
	});
	document.addEventListener('click', function(e){
		that.hide(e);
	});
};
CT_MENU_MOD.fn.init = function(){
	this.handle();
}
window.YanCtMenu = CT_MENU_MOD;
}(window);